<template>
  <el-form
    ref="userForm"
    :model="userInfo"
    label-width="120px"
    :rules="rules"
    style="margin-left: 120px; margin-top: 30px"
  >
    <el-form-item label="姓名:"  prop="username">
      <el-input v-model="userInfo.username" style="width:300px" />
    </el-form-item>
    <el-form-item label="密码:" prop="password">
      <el-input v-model="userInfo.password" type="password" style="width:300px" />
    </el-form-item>
 
    <el-form-item>
      <el-button type="primary"  @click="hSubmit">更新</el-button>
    </el-form-item>
 </el-form>
</template>
<script>
  import { getUserDetailById } from '@/api/user'
  import { saveUserDetailById } from '@/api/employees.js'
  export default {
    data() {
        return {
          userId: this.$route.params.id, // 路径参数的接收方式
          userInfo: {
              username: '',
              password: ''
            },
          rules: {
            username: [{ required: true, message: '用户名不能为空', triggler: 'blur' }],
            password: [{ required: true, message: '密码不能为空', triggler: 'blur' }]
         }
        }
      },
    created() {
       this.loadUserDetailById()
      },
    methods: {
      hSubmit() {
      this.$refs.userForm.validate(valid => {
        if (!valid) return
         this.updateUserDetailById()
       })
      },
       // 获取用户信息填充到表单
      async loadUserDetailById() {
      try {
        const res = await getUserDetailById(this.userId)
        console.log('getUserDetailById', res)
        // this.userInfo = { ...res.data, password: '' } // 密码为空
        this.userInfo = res.data
      } catch (error) {
        console.log('getUserDetailById', error)
      }
      },
       // 更新用户信息
    async updateUserDetailById() {
      try {
        const res = await saveUserDetailById(this.userInfo)
        console.log('saveUserDetailById', res)
        this.$router.back()
      } catch (error) {
        console.log('saveUserDetailById', error)
      }
    }
    }
  }
</script>